/**
 * 
 */
package Generators;

import java.io.BufferedWriter;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import javax.xml.bind.DatatypeConverter;

/**
 * @author ASUS
 *
 */
public class DSAPrivateKey extends DSAKey {
	private BigInteger x;
	
	public DSAPrivateKey(DSAParameters dsaParameters, BigInteger privKey) {
		super(dsaParameters);
		x = privKey;
	}
	
	
	public String toString(){
		//Get DSA Parameters's informations
		StringBuffer sf = new StringBuffer(getParameters().toString());
		//Append private key's informations
		sf.append("Private Key\n");
		sf.append("\tSize : " + x.bitLength() + "\n");
		sf.append("\tValue: " + x.toString(16) + "\n");
		
		return sf.toString();
	}
	
	/* (non-Javadoc)
	 * @see Generators.DSAKey#exportToFile(java.lang.String)
	 */
	@Override
	public int exportToFile(String fileName) {
		Charset charset = Charset.forName("US-ASCII");
		try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(fileName), charset, StandardOpenOption.CREATE)) {
			String s = toString();
			writer.write("-----BEGIN PRIVATE KEY-----\n");
			writer.write(DatatypeConverter.printBase64Binary(s.getBytes()));
			//writer.write(s);
			writer.write("\n-----END PRIVATE KEY-----\n");
			writer.close();
			return 1;		
		} catch (IOException x) {
		    System.err.format("IOException: %s%n", x);
			return -1;
		}
	}

	/* (non-Javadoc)
	 * @see Generators.DSAKey#getValue()
	 */
	@Override
	public BigInteger getValue() {
		// TODO Auto-generated method stub
		return x;
	}

}
